package com.xywh.wanandroid.util

import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.annotation.RequiresApi
import androidx.core.content.FileProvider
import androidx.fragment.app.Fragment
import java.io.File


/**
 * <pre>
 * author: Fan
 * time  : 2018/1/7 下午4:56
 * desc  : android安装应用(适用于各个版本)
</pre> *
 */
class InstallUtil(
    private val mAct: Fragment, //下载下来后文件的路径
    private val mPath: String
) {
    fun install() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) startInstallO() else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) startInstallN() else startInstall()
    }

    /**
     * android1.x-6.x
     */
    private fun startInstall() {
        val install = Intent(Intent.ACTION_VIEW)
        install.setDataAndType(
            Uri.parse("file://$mPath"),
            "application/vnd.android.package-archive"
        )
        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        mAct.startActivity(install)
    }

    /**
     * android7.x
     */
    private fun startInstallN() {
        //参数1 上下文, 参数2 在AndroidManifest中的android:authorities值, 参数3  共享的文件
        val apkUri: Uri =
            FileProvider.getUriForFile(
                mAct.requireContext(),
                "com.xywh.heshui.fileprovider",
                File(mPath)
            )
        val install = Intent(Intent.ACTION_VIEW)
        //由于没有在Activity环境下启动Activity,设置下面的标签
        install.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        //添加这一句表示对目标应用临时授权该Uri所代表的文件
        install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        install.setDataAndType(apkUri, "application/vnd.android.package-archive")
        mAct.startActivity(install)
    }

    /**
     * android8.x
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private fun startInstallO() {
        val isGranted = mAct.requireContext().packageManager.canRequestPackageInstalls()
        if (isGranted) startInstallN() //安装应用的逻辑(写自己的就可以)
        else AlertDialog.Builder(mAct.requireContext())
            .setCancelable(false)
            .setTitle("安装应用需要打开未知来源权限，请去设置中开启权限")
            .setPositiveButton("确定", DialogInterface.OnClickListener { d, w ->
                val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES)
                mAct.startActivityForResult(intent, UNKNOWN_CODE)
            })
            .show()
    }

    companion object {
        var UNKNOWN_CODE = 2018
    }
}


